<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简易问答</title>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js" defer></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js" defer></script>

    <style>
        body { font-family: sans-serif; margin: 0; display: flex; height: 100vh; background-color: #f8f9fa; color: #212529; font-size: 14px; }
        #sidebar { width: 260px; background-color: #343a40; color: #dee2e6; border-right: 1px solid #495057; padding: 15px; display: flex; flex-direction: column; }
        #chat-container { flex-grow: 1; display: flex; flex-direction: column; height: 100%; background-color: #f8f9fa; }
        #chatbox { flex-grow: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 15px; }

        .message { padding: 0; border-radius: 15px; max-width: 85%; word-wrap: break-word; line-height: 1.5; position: relative; }
        .message-content-wrapper { padding: 10px 15px; border-radius: 15px; white-space: pre-wrap; word-break: break-all; }

        .user-message { background-color: #007bff; color: white; align-self: flex-end; border-bottom-right-radius: 0; }
        .user-message .message-content-wrapper { background-color: #007bff; color: white; border-bottom-right-radius: 0; }

        .model-message { background-color: #ffffff; border: 1px solid #dee2e6; align-self: flex-start; border-bottom-left-radius: 0; color: #343a40; }
        .model-message .message-content-wrapper { background-color: #ffffff; border-bottom-left-radius: 0; }
        .error-message { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; align-self: flex-start; white-space: pre-wrap;}
        .error-message .message-content-wrapper { background-color: #f8d7da; color: #721c24; }

        #input-area { 
            display: flex; 
            padding: 15px; 
            border-top: 1px solid #dee2e6; 
            background-color: #ffffff; 
            flex-direction: column;
        }
        
        #images-preview-container {
            display: none;
            margin-bottom: 10px;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .image-preview-item {
            position: relative;
            width: 80px;
            height: 80px;
        }
        
        .image-preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 5px;
            border: 2px solid #dee2e6;
        }
        
        .remove-image-btn {
            position: absolute;
            top: -5px;
            right: -5px;
            background-color: rgba(220, 53, 69, 0.9);
            color: white;
            border: none;
            border-radius: 50%;
            width: 22px;
            height: 22px;
            cursor: pointer;
            font-size: 14px;
            line-height: 22px;
            text-align: center;
            font-weight: bold;
        }
        
        .remove-image-btn:hover {
            background-color: rgba(220, 53, 69, 1);
        }
        
        #input-controls {
            display: flex;
            width: 100%;
            align-items: center;
        }
        
        #message-input { flex-grow: 1; padding: 10px; border: 1px solid #ced4da; border-radius: 5px; resize: none; min-height: 24px; max-height: 150px; overflow-y: auto; background-color: #fff; color: #495057; line-height: 1.4; }
        #upload-button, #send-button { background-color: #0d6efd; color: white; border: none; padding: 0 15px; height: 40px; border-radius: 5px; margin-left: 10px; cursor: pointer; display: flex; align-items: center; justify-content: center; flex-shrink: 0;}
        #upload-button {
            background-color: #6c757d;
            padding: 0;
            width: 40px;
            margin-left: 0;
        }
        #upload-button svg {
            width: 20px;
            height: 20px;
        }
        #send-button:disabled { background-color: #6c757d; cursor: not-allowed; }
        #new-chat-button, #add-command-button { background-color: rgba(255, 255, 255, 0.1); color: #f8f9fa; border: 1px solid rgba(255, 255, 255, 0.2); padding: 8px 15px; border-radius: 5px; cursor: pointer; margin-bottom: 10px; text-align: center; width: 100%; box-sizing: border-box;}
        #new-chat-button:hover, #add-command-button:hover { background-color: rgba(255, 255, 255, 0.2); }

        .sidebar-section { margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #495057; }
        .sidebar-section:last-of-type { border-bottom: none; }
        .sidebar-section h3 { font-size: 0.85em; color: #adb5bd; margin-top: 0; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.5px;}
        .command-list { list-style: none; padding: 0; margin: 0; max-height: 250px; overflow-y: auto; }
        .command-list li { padding: 6px 5px; border-radius: 4px; font-size: 0.9em; display: flex; justify-content: space-between; align-items: center; gap: 5px;}
        .command-list li:hover { background-color: rgba(255, 255, 255, 0.1); }
        .command-name { flex-grow: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer; }
        .command-actions button { background: none; border: none; color: #adb5bd; cursor: pointer; padding: 2px 4px; font-size: 0.8em; line-height: 1;}
        .command-actions button:hover { color: #f8f9fa; }

        .controls { padding-top: 15px; }
        .control-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-size: 0.9em; color: #adb5bd; }
        select { padding: 8px; border-radius: 4px; border: 1px solid #495057; width: 100%; background-color: #495057; color: #dee2e6; box-sizing: border-box;}

        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.6); display: none; align-items: center; justify-content: center; z-index: 1000; }
        .modal-content { background-color: #212529; color: #dee2e6; padding: 25px; border-radius: 8px; width: 90%; max-width: 450px; box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
        .modal-content h2 { margin-top: 0; color: #f8f9fa; border-bottom: 1px solid #495057; padding-bottom: 10px; margin-bottom: 20px; font-size: 1.2em;}
        .modal-field { margin-bottom: 15px; }
        .modal-field label { display: block; margin-bottom: 5px; font-size: 0.9em; color: #adb5bd; }
        .modal-field label span { color: #dc3545; }
        .modal-field input[type="text"], .modal-field textarea { width: 100%; padding: 10px; border: 1px solid #495057; border-radius: 4px; background-color: #343a40; color: #dee2e6; box-sizing: border-box; font-size: 0.95em;}
        .modal-field textarea { resize: vertical; min-height: 80px; }
        .modal-buttons { text-align: right; margin-top: 20px; }
        .modal-buttons button { padding: 8px 15px; border: none; border-radius: 4px; cursor: pointer; margin-left: 10px; font-size: 0.9em; }
        .modal-save-button { background-color: #28a745; color: white; }
        .modal-cancel-button { background-color: #6c757d; color: white; }
        .modal-error { color: #dc3545; font-size: 0.85em; margin-top: 10px; display: none; }

        .model-message .message-content-wrapper pre {
            background-color: #212529;
            color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
            position: relative;
            margin: 10px 0;
        }
        .model-message .message-content-wrapper code {
             font-family: monospace;
             font-size: 0.9em;
             background: none;
             color: inherit;
             padding: 0;
        }
        .model-message .message-content-wrapper :not(pre) > code {
            background-color: rgba(0,0,0,0.06);
            padding: 2px 4px;
            border-radius: 3px;
            font-size: 0.9em;
        }
        .copy-button {
            position: absolute;
            top: 5px;
            right: 5px;
            background-color: rgba(255, 255, 255, 0.15);
            color: #adb5bd;
            border: none;
            border-radius: 4px;
            padding: 3px 8px;
            font-size: 0.75em;
            cursor: pointer;
            opacity: 0;
            transition: opacity 0.2s ease-in-out, background-color 0.2s;
            z-index: 10;
        }
        .message:hover .copy-button {
            opacity: 1;
        }
        .copy-button:hover {
            background-color: rgba(255, 255, 255, 0.3);
            color: #f8f9fa;
        }
        .copy-button.code-copy-button {
            top: 8px;
            right: 8px;
            background-color: #555;
            color: white;
            opacity: 0.7;
        }
         .message .message-content-wrapper pre:hover .code-copy-button {
             opacity: 1;
         }
         .copy-button.copied {
            background-color: #28a745;
            color: white;
         }

        #group-chat-button {
            position: fixed;
            bottom: 180px;
            right: 25px;
            width: 60px;
            height: 60px;
            background-color: #0d6efd;
            color: white;
            border: none;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            cursor: pointer;
            z-index: 1001;
            transition: background-color 0.3s;
        }
        #group-chat-button:hover {
            background-color: #0056b3;
        }
        #group-chat-button svg {
            width: 28px;
            height: 28px;
        }
        
        .user-message .user-images {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin-top: 5px;
        }
        
        .user-message .user-images img {
            max-width: 150px;
            max-height: 150px;
            border-radius: 5px;
        }

    </style>
</head>
<body>
    <div id="sidebar">
        <button id="new-chat-button">新建聊天</button>

        <div class="sidebar-section">
            <h3>命令管理</h3>
            <ul id="command-list" class="command-list">
            </ul>
            <button id="add-command-button" style="margin-top: 10px;">新建命令</button>
        </div>

        <div class="controls sidebar-section">
             <h3>设置</h3>
             <div class="control-group">
                <label for="model-select">选择模型:</label>
                <select id="model-select">
                    {% for model in models %}
                        <option value="{{ model }}" {% if model == default_model %}selected{% endif %}>{{ model }}</option>
                    {% endfor %}
                </select>
             </div>
        </div>
    </div>

    <div id="chat-container">
        <div id="chatbox">
             <div class="message model-message">
                 <div class="message-content-wrapper">你好！有什么可以帮你的吗？</div>
             </div>
        </div>
        <div id="input-area">
            <div id="images-preview-container"></div>
            <div id="input-controls">
                <input type="file" id="image-upload" accept="image/*" multiple style="display: none;">
                <label for="image-upload" id="upload-button" title="上传图片(可多选)">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14m-7-7h14"/></svg>
                </label>
                <textarea id="message-input" placeholder="输入消息... (Shift+Enter 换行)" rows="1"></textarea>
                <button id="send-button" title="发送">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"> <path d="M15.854.146a.5.5 0 0 1 .11.54l-5.819 14.547a.75.75 0 0 1-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 0 1 .124-1.33L15.314.037a.5.5 0 0 1 .54.11ZM6.636 10.07l2.761 4.338L14.13 2.576zm6.787-8.201L1.591 6.602l4.339 2.76z"/> </svg>
                </button>
            </div>
        </div>
    </div>

    <div id="command-modal" class="modal-overlay">
        <div class="modal-content">
            <h2 id="modal-title">新建命令</h2>
            <input type="hidden" id="command-id">
            <div id="modal-error-message" class="modal-error"></div>
            <div class="modal-field">
                <label for="command-name"><span>*</span> 名称:</label>
                <input type="text" id="command-name" required>
            </div>
            <div class="modal-field">
                <label for="command-text"><span>*</span> 命令:</label>
                <textarea id="command-text" required></textarea>
            </div>
            <div class="modal-buttons">
                <button id="modal-cancel-button" class="modal-cancel-button">取消</button>
                <button id="modal-save-button" class="modal-save-button">保存</button>
            </div>
        </div>
    </div>

    <a id="group-chat-button" href="/group-chat" title="公共聊天室" target="_blank">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-message-square"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>
    </a>

    <script>
        const chatbox = document.getElementById('chatbox');
        const messageInput = document.getElementById('message-input');
        const sendButton = document.getElementById('send-button');
        const newChatButton = document.getElementById('new-chat-button');
        const modelSelect = document.getElementById('model-select');
        const commandListUl = document.getElementById('command-list');
        const addCommandButton = document.getElementById('add-command-button');
        const commandModal = document.getElementById('command-modal');
        const modalTitle = document.getElementById('modal-title');
        const modalCancelButton = document.getElementById('modal-cancel-button');
        const modalSaveButton = document.getElementById('modal-save-button');
        const commandIdInput = document.getElementById('command-id');
        const commandNameInput = document.getElementById('command-name');
        const commandTextInput = document.getElementById('command-text');
        const modalErrorMessage = document.getElementById('modal-error-message');
        
        const imageUploadInput = document.getElementById('image-upload');
        const imagesPreviewContainer = document.getElementById('images-preview-container');

        let chatHistory = [];
        let savedCommands = [];
        let currentEditCommandId = null;
        let selectedImages = [];

        function copyToClipboard(text, buttonElement) {
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(text).then(() => {
                    const originalText = buttonElement.textContent;
                    buttonElement.textContent = '已复制!';
                    buttonElement.classList.add('copied');
                    setTimeout(() => {
                        buttonElement.textContent = originalText;
                        buttonElement.classList.remove('copied');
                    }, 1500);
                }).catch(err => {
                    console.error('Failed to copy text using navigator: ', err);
                    fallbackCopyToClipboard(text, buttonElement);
                });
            } else {
                fallbackCopyToClipboard(text, buttonElement);
            }
        }

        function fallbackCopyToClipboard(text, buttonElement) {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.top = 0;
            textArea.style.left = 0;
            textArea.style.width = '2em';
            textArea.style.height = '2em';
            textArea.style.padding = 0;
            textArea.style.border = 'none';
            textArea.style.outline = 'none';
            textArea.style.boxShadow = 'none';
            textArea.style.background = 'transparent';

            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    const originalText = buttonElement.textContent;
                    buttonElement.textContent = '已复制!';
                    buttonElement.classList.add('copied');
                    setTimeout(() => {
                        buttonElement.textContent = originalText;
                        buttonElement.classList.remove('copied');
                    }, 1500);
                } else {
                    alert('复制失败!');
                }
            } catch (err) {
                console.error('Fallback: Oops, unable to copy', err);
                alert('复制失败!');
            }

            document.body.removeChild(textArea);
        }

        function addMessageButtons(messageElement, rawContent) {
            const copyButton = document.createElement('button');
            copyButton.textContent = '复制';
            copyButton.classList.add('copy-button');
            copyButton.addEventListener('click', (e) => {
                e.stopPropagation();
                copyToClipboard(rawContent, copyButton);
            });
            messageElement.appendChild(copyButton);

            const codeBlocks = messageElement.querySelectorAll('pre');
            codeBlocks.forEach(pre => {
                const code = pre.querySelector('code');
                if (code) {
                    const codeCopyButton = document.createElement('button');
                    codeCopyButton.textContent = '复制';
                    codeCopyButton.classList.add('copy-button', 'code-copy-button');
                    codeCopyButton.addEventListener('click', (e) => {
                        e.stopPropagation();
                        copyToClipboard(code.textContent, codeCopyButton);
                    });

                    if (window.getComputedStyle(pre).position === 'static') {
                        pre.style.position = 'relative';
                    }
                    pre.appendChild(codeCopyButton);
                }
            });
        }

        function appendMessageToChatbox(role, text, imageUrls = []) {
            const messageDiv = document.createElement('div');
            messageDiv.classList.add('message', `${role}-message`);
            
            const contentWrapper = document.createElement('div');
            contentWrapper.classList.add('message-content-wrapper');
            
            if (text) {
                const textNode = document.createElement('div');
                textNode.textContent = text;
                contentWrapper.appendChild(textNode);
            }
            
            if (imageUrls.length > 0) {
                const imagesContainer = document.createElement('div');
                imagesContainer.classList.add('user-images');
                imageUrls.forEach(url => {
                    const img = document.createElement('img');
                    img.src = url;
                    imagesContainer.appendChild(img);
                });
                contentWrapper.appendChild(imagesContainer);
            }
            
            messageDiv.appendChild(contentWrapper);
            chatbox.appendChild(messageDiv);
            chatbox.scrollTop = chatbox.scrollHeight;
            return { messageDiv, contentWrapper };
        }
        
        async function sendMessage() {
            const userInput = messageInput.value.trim();
            if (!userInput && selectedImages.length === 0) return;

            const tempImageUrls = selectedImages.map(file => URL.createObjectURL(file));
            appendMessageToChatbox('user', userInput, tempImageUrls);
            
            const formData = new FormData();
            formData.append('user_input', userInput);
            formData.append('history', JSON.stringify(chatHistory));
            formData.append('model_name', modelSelect.value);
            
            selectedImages.forEach(file => {
                formData.append('images', file);
            });

            messageInput.value = '';
            clearImagesPreview();
            adjustTextareaHeight();
            sendButton.disabled = true;

            const { messageDiv: modelMessageDiv, contentWrapper: modelContentWrapper } = appendMessageToChatbox('model', '...');
            let accumulatedResponse = '';
            let hasError = false;

            try {
                const response = await fetch('/chat', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok || !response.body) {
                    const errorData = await response.json().catch(() => ({error: `HTTP error ${response.status}`}));
                    throw new Error(errorData.error || `HTTP error ${response.status}`);
                }
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                modelContentWrapper.textContent = '';

                while (true) {
                    const { value, done } = await reader.read();
                    if (done) break;

                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n\n');
                    buffer = lines.pop() || ''; 
                    
                    for (const line of lines) {
                        if (line.startsWith('data:')) {
                            try {
                                const jsonData = JSON.parse(line.substring(5).trim());
                                if (jsonData.end) {
                                    break; 
                                }
                                if (jsonData.text) {
                                    accumulatedResponse += jsonData.text;
                                    modelContentWrapper.innerHTML = marked.parse(accumulatedResponse);
                                    chatbox.scrollTop = chatbox.scrollHeight;
                                } else if (jsonData.error) {
                                    throw new Error(jsonData.error);
                                }
                            } catch (e) {
                                console.warn("Error parsing stream data:", e, "Data:", line);
                            }
                        }
                    }
                }

            } catch (error) {
                console.error('Chat error:', error);
                modelContentWrapper.textContent = `错误: ${error.message}`;
                modelMessageDiv.classList.add('error-message');
                accumulatedResponse = '';
                hasError = true;
            } finally {
                const userHistoryPart = [];
                if (userInput) userHistoryPart.push(userInput);

                if (accumulatedResponse && !hasError) {
                    chatHistory.push({ role: 'user', parts: userHistoryPart });
                    chatHistory.push({ role: 'model', parts: [accumulatedResponse] });
                    
                    modelContentWrapper.innerHTML = marked.parse(accumulatedResponse);
                    modelContentWrapper.querySelectorAll('pre code').forEach((block) => {
                       Prism.highlightElement(block);
                    });
                    addMessageButtons(modelMessageDiv, accumulatedResponse);
                } else {
                    if (modelContentWrapper.textContent === '' || modelContentWrapper.textContent === '...') {
                       modelContentWrapper.textContent = '(无回复或发生错误)';
                       modelMessageDiv.classList.add('error-message');
                    }
                }
                
                sendButton.disabled = false;
                messageInput.focus();
                chatbox.scrollTop = chatbox.scrollHeight;
            }
        }

        async function loadCommands() {
            try {
                const response = await fetch('/api/commands');
                if (!response.ok) {
                    throw new Error('Failed to fetch commands');
                }
                savedCommands = await response.json();
                renderCommands();
            } catch (error) {
                console.error('Failed to load commands:', error);
            }
        }

        function renderCommands() {
            commandListUl.innerHTML = '';
            savedCommands.forEach(cmd => {
                const li = document.createElement('li');
                li.dataset.commandId = cmd.id;

                const nameSpan = document.createElement('span');
                nameSpan.className = 'command-name';
                nameSpan.textContent = cmd.name;
                nameSpan.title = `点击应用: ${cmd.command}`;
                nameSpan.onclick = () => {
                    if (messageInput.value) {
                        messageInput.value += ' ' + cmd.command;
                    } else {
                        messageInput.value = cmd.command;
                    }
                    adjustTextareaHeight();
                    messageInput.focus();
                };

                const actionsDiv = document.createElement('div');
                actionsDiv.className = 'command-actions';
                
                const editButton = document.createElement('button');
                editButton.innerHTML = '&#9998;';
                editButton.title = "编辑";
                editButton.onclick = (e) => { e.stopPropagation(); openCommandModal(cmd.id); };

                const deleteButton = document.createElement('button');
                deleteButton.innerHTML = '&#128465;';
                deleteButton.title = "删除";
                deleteButton.onclick = (e) => { e.stopPropagation(); deleteCommand(cmd.id); };

                actionsDiv.appendChild(editButton);
                actionsDiv.appendChild(deleteButton);
                li.appendChild(nameSpan);
                li.appendChild(actionsDiv);
                commandListUl.appendChild(li);
            });
        }

        function openCommandModal(commandId = null) {
            commandIdInput.value = commandId || '';
            currentEditCommandId = commandId;
            modalErrorMessage.style.display = 'none';

            if (commandId) {
                const command = savedCommands.find(c => c.id === commandId);
                modalTitle.textContent = '编辑命令';
                commandNameInput.value = command.name;
                commandTextInput.value = command.command;
            } else {
                modalTitle.textContent = '新建命令';
                commandNameInput.value = '';
                commandTextInput.value = '';
            }
            commandModal.style.display = 'flex';
        }

        function closeCommandModal() {
            commandModal.style.display = 'none';
        }

        async function saveCommand() {
            const name = commandNameInput.value.trim();
            const commandText = commandTextInput.value.trim();
            const id = currentEditCommandId;

            if (!name || !commandText) {
                modalErrorMessage.textContent = '名称和命令不能为空。';
                modalErrorMessage.style.display = 'block';
                return;
            }
            modalErrorMessage.style.display = 'none';

            const url = id ? `/api/commands/${id}` : '/api/commands';
            const method = id ? 'PUT' : 'POST';

            try {
                const response = await fetch(url, {
                    method: method,
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ name: name, command: commandText })
                });
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || '保存失败');
                }
                await loadCommands();
                closeCommandModal();
            } catch (error) {
                console.error('Failed to save command:', error);
                modalErrorMessage.textContent = error.message;
                modalErrorMessage.style.display = 'block';
            }
        }

        async function deleteCommand(commandId) {
            if (!confirm('确定要删除这个命令吗?')) return;
            try {
                const response = await fetch(`/api/commands/${commandId}`, { method: 'DELETE' });
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || '删除失败');
                }
                await loadCommands();
            } catch (error) {
                console.error('Failed to delete command:', error);
                alert(error.message);
            }
        }
        
        function adjustTextareaHeight() {
            messageInput.style.height = 'auto';
            const newHeight = Math.min(messageInput.scrollHeight, 150);
            messageInput.style.height = `${newHeight}px`;
        }

        function showImagesPreview(files) {
            selectedImages = Array.from(files);
            updateImagesPreview();
        }

        function updateImagesPreview() {
            imagesPreviewContainer.innerHTML = '';
            
            if (selectedImages.length === 0) {
                imagesPreviewContainer.style.display = 'none';
                return;
            }
            
            imagesPreviewContainer.style.display = 'flex';
            
            selectedImages.forEach((file, index) => {
                const reader = new FileReader();
                reader.onload = (e) => {
                    const previewItem = document.createElement('div');
                    previewItem.classList.add('image-preview-item');
                    
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    
                    const removeBtn = document.createElement('button');
                    removeBtn.classList.add('remove-image-btn');
                    removeBtn.textContent = '×';
                    removeBtn.onclick = () => removeImage(index);
                    
                    previewItem.appendChild(img);
                    previewItem.appendChild(removeBtn);
                    imagesPreviewContainer.appendChild(previewItem);
                };
                reader.readAsDataURL(file);
            });
        }

        function removeImage(index) {
            selectedImages.splice(index, 1);
            updateImagesPreview();
        }

        function clearImagesPreview() {
            selectedImages = [];
            imageUploadInput.value = '';
            imagesPreviewContainer.innerHTML = '';
            imagesPreviewContainer.style.display = 'none';
        }

        sendButton.addEventListener('click', sendMessage);
        messageInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        newChatButton.addEventListener('click', () => {
            chatbox.innerHTML = `
                <div class="message model-message">
                    <div class="message-content-wrapper">你好！有什么可以帮你的吗？</div>
                </div>`;
            chatHistory = [];
            clearImagesPreview();
        });
        
        addCommandButton.addEventListener('click', () => openCommandModal());
        modalCancelButton.addEventListener('click', closeCommandModal);
        modalSaveButton.addEventListener('click', saveCommand);
        commandModal.addEventListener('click', (e) => {
            if (e.target === commandModal) {
                closeCommandModal();
            }
        });

        imageUploadInput.addEventListener('change', (e) => {
            if (e.target.files && e.target.files.length > 0) {
                showImagesPreview(e.target.files);
            }
        });

        document.addEventListener('paste', (e) => {
            const items = (e.clipboardData || e.originalEvent.clipboardData).items;
            const pastedFiles = [];
            
            for (const item of items) {
                if (item.kind === 'file' && item.type.startsWith('image/')) {
                    pastedFiles.push(item.getAsFile());
                }
            }

            if (pastedFiles.length > 0) {
                e.preventDefault();
                // 追加新粘贴的图片到已有图片列表
                selectedImages = [...selectedImages, ...pastedFiles];
                updateImagesPreview();
                messageInput.focus();
            }
        });

        loadCommands();
        messageInput.addEventListener('input', adjustTextareaHeight);

        marked.setOptions({
            breaks: true,
            gfm: true,
        });

    </script>
</body>
</html>